﻿Imports System.Text
Imports System.Net
Imports System.Net.Sockets

Namespace Coding4Fun.PrinterDisplayHack
	Public Class SendToPrinter
		Public Property Host() As String

		Public Function Send(ByVal message As String) As Integer
			Dim endPoint As IPEndPoint = Nothing

			Try
				Dim addr As IPAddress = Dns.GetHostAddresses(Host)(0)

				endPoint = New IPEndPoint(addr, 9100)
			Catch
				Return 1
			End Try

			Dim startPJLSequence As String = ChrW(&H1B).ToString() & "%-12345X@PJL RDYMSG DISPLAY = """
			Dim endPJLSequence As String = """" & vbCrLf & ChrW(&H1B).ToString() & "%-12345X" & vbCrLf

			Dim encoding As New ASCIIEncoding()

			Try
				Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)

				sock.Connect(endPoint)

				sock.Send(encoding.GetBytes(startPJLSequence))
				sock.Send(encoding.GetBytes(message))
				sock.Send(encoding.GetBytes(endPJLSequence))

				sock.Close()
			Catch
				Return 1
			End Try

			Return 0
		End Function
	End Class
End Namespace
